package com.starhub.application.rag.service.impl;

import java.util.List;

import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.starhub.application.rag.dto.SegmentDto;
import com.starhub.application.rag.entity.Segment;
import com.starhub.application.rag.mapper.SegmentMapper;
import com.starhub.application.rag.service.SegmentService;
import com.starhub.engine.generator.genid.IdGenerator;
import com.starhub.utils.HubBeanUtils;

import lombok.extern.slf4j.Slf4j;

/**
 * 段落服务实现类
 * @version: V1.0
 * @author: liuhf
 * @time 2025-06-05
 */
@Slf4j
@Service
public class SegmentServiceImpl extends ServiceImpl<SegmentMapper, Segment> implements SegmentService {

    @Override
    public Long create(SegmentDto segmentDto) {
        //生成ID
        Long id = IdGenerator.generateId();
        Segment segment = HubBeanUtils.convert(segmentDto, Segment.class);
        segment.setId(id);
        segment.setDeleteType(0); // 设置初始状态为未删除
        boolean flag = this.save(segment);
        return flag ? id : null;
    }

    @Override
    public void batchCreate(List<SegmentDto> segments) {
        if (segments == null || segments.isEmpty()) {
            return;
        }
        List<Segment> segmentList = segments.stream()
                .map(dto -> {
                    Segment segment = HubBeanUtils.convert(dto, Segment.class);
                    segment.setId(IdGenerator.generateId());
                    segment.setDeleteType(0); // 设置初始状态为未删除
                    return segment;
                })
                .toList();
        this.saveBatch(segmentList);
    }

    @Override
    public void deleteByItemId(Long itemId) {
        // 根据itemId软删除
        Segment segment = new Segment();
        segment.setDeleteType(1);
        LambdaQueryWrapper<Segment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Segment::getItemId, itemId)
                   .eq(Segment::getDeleteType, 0); // 只更新未删除的记录
        this.update(segment, queryWrapper);
    }

    @Override
    public void deleteByCollectionId(Long collectionId) {
        // 根据collectionId软删除
        Segment segment = new Segment();
        segment.setDeleteType(1);
        LambdaQueryWrapper<Segment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Segment::getCollectionId, collectionId)
                   .eq(Segment::getDeleteType, 0); // 只更新未删除的记录
        this.update(segment, queryWrapper);
    }

    @Override
    public void deleteByBaseId(Long baseId) {
        // 根据baseId软删除
        Segment segment = new Segment();
        segment.setDeleteType(1);
        LambdaQueryWrapper<Segment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Segment::getBaseId, baseId)
                   .eq(Segment::getDeleteType, 0); // 只更新未删除的记录
        this.update(segment, queryWrapper);
    }

    @Override
    public List<Segment> listByIds(List<String> ids) {
        // 重写listByIds方法，添加未删除条件
        LambdaQueryWrapper<Segment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Segment::getId, ids)
                   .eq(Segment::getDeleteType, 0);
        return this.list(queryWrapper);
    }

    @Override
    public void batchUpdate(List<SegmentDto> segmentDtos) {
        if (segmentDtos == null || segmentDtos.isEmpty()) {
            log.warn("Cannot update segment metadata: segmentDtos is null or empty");
            return;
        }

        try {
            // 批量更新
            for (SegmentDto segmentDto : segmentDtos) {
                if (segmentDto.getId() == null) {
                    log.warn("Cannot update segment metadata: segment id is null");
                    continue;
                }

                // 创建更新对象
                Segment segment = new Segment();
                segment.setSegmentMetadata(segmentDto.getSegmentMetadata());

                // 构建更新条件
                LambdaQueryWrapper<Segment> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(Segment::getId, segmentDto.getId())
                           .eq(Segment::getDeleteType, 0); // 只更新未删除的记录

                // 执行更新
                boolean success = this.update(segment, queryWrapper);
                if (!success) {
                    log.warn("Failed to update segment metadata for id: {}", segmentDto.getId());
                } else {
                    log.info("Successfully updated segment metadata for id: {}", segmentDto.getId());
                }
            }
        } catch (Exception e) {
            log.error("Error updating segment metadata", e);
            throw new RuntimeException("Failed to update segment metadata: " + e.getMessage(), e);
        }
    }
}
